/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package common;

import com.icegreen.greenmail.util.GreenMail;
import com.icegreen.greenmail.util.ServerSetupTest;
import java.io.IOException;
import java.util.Properties;
import javax.mail.AuthenticationFailedException;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author 04400099
 */
@WebServlet(name = "MailServlet", urlPatterns = {"/InviaMail"})
public class MailServlet extends HttpServlet {

    private static GreenMail mailServer;
    private static final String EMAIL_USER_ADDRESS = "info@uninsieme.it";
    private static final String USER_NAME = "uninsieme";
    private static final String USER_PASSWORD = "federico";

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        if (mailServer == null) {
            // start del server smtp
            mailServer = new GreenMail(ServerSetupTest.IMAP);
            mailServer.setUser(EMAIL_USER_ADDRESS, USER_NAME, USER_PASSWORD);
        }
        String from = "info@uninsieme.it"; //request.getParameter("email");
        String to = "fedfus@gmail.com";//request.getParameter("email");
        String subject = request.getParameter("object");
        String message = request.getParameter("message");

        try {
            Properties props = new Properties();
            props.setProperty("mail.host", "127.0.0.1");
            props.setProperty("mail.smtp.auth", "true");
            props.setProperty("mail.smtp.port", String.valueOf(ServerSetupTest.SMTP.getPort()));
            props.setProperty("mail.smtp.starttls.enable", "true");

            Authenticator auth = new SMTPAuthenticator(USER_NAME, USER_PASSWORD);

            Session session = Session.getInstance(props, auth);

            MimeMessage msg = new MimeMessage(session);
            msg.setText(message);
            msg.setSubject(subject);
            msg.setFrom(new InternetAddress(from));
            msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            Transport.send(msg);

        } catch (AuthenticationFailedException ex) {
            request.setAttribute("ErrorMessage", "Authentication failed");

        } catch (AddressException ex) {
            request.setAttribute("ErrorMessage", "Wrong email address");

        } catch (MessagingException ex) {
            request.setAttribute("ErrorMessage", ex.getMessage());
        }

    }

    private class SMTPAuthenticator extends Authenticator {

        private PasswordAuthentication authentication;

        public SMTPAuthenticator(String login, String password) {
            authentication = new PasswordAuthentication(login, password);
        }

        protected PasswordAuthentication getPasswordAuthentication() {
            return authentication;
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Mail";
    }// </editor-fold>

}
